import React from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  TouchableWithoutFeedback,
  FlatList,
  Image,
  Dimensions,
  StatusBar,
} from 'react-native';
import {Actions} from 'react-native-router-flux';
import CommonStyles from '../../common/styles';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import api from '../../common/api';
import util from '../../common/util';
import {AlbumView, Overlay, PullPicker} from 'teaset';
import {Avatar, Divider } from 'react-native-elements';
import Button from 'antd-mobile/lib/button';

const {width, height} = Dimensions.get('window');

export default class TopicScreen extends React.Component {
  static onEnter = (props) => {
    console.log("TopicScreen onEnter", props);
    Actions.refresh({
      onRight: () => {
        Actions.TopicCreate({router_params: {forum: props.router_params.forum}});
      }
    })
  }
  constructor(props) {
    console.log("TopicScreen constructor");
    super(props);
    this.state = {
      orderType: null,
      loading: false,
      params: props.router_params.forum,
      forumInfo: [],
      list: [],
      page: 1,
      include_forum: true,
    }
  }

  componentWillReceiveProps(props) {
    console.log("componentWillReceiveProps", props);
    if (props.refresh) {
      this.onRefresh();
    }
  }

  componentDidMount() {
    this.setState({
      loading: true,
    }, () => {
      this.fetchTopics();
    });
  }

  onRefresh() {
    this.setState({
      loading: true,
      page: 1,
    }, () => {
      this.fetchTopics();
    })
  }

  fetchTopics() {
    var self = this;
    let queryString = "forum_key=" + this.state.params.key + "&page=" + this.state.page;
    if (this.state.include_forum) {
      queryString += "&include_forum=1";
    }
    api.listTopic(queryString)
    .then((response) => {
      console.log(response);
      self.setState({
        loading: false,
        include_forum: false,
      });
      if (response.ret == 0) {
        if (response.data.pagination.current_page == 1) {
          var newList = response.data.list;
        } else {
          var newList = [...self.state.list, ...response.data.list];
        }
        let newState = {
          list: newList,
          pagination: response.data.pagination,
          page: response.data.pagination.current_page + 1,
        }
        if (response.data.forum) {
          newState.forumInfo = response.data.forum.data;
        }
        self.setState(newState);
      } else {
        Toast.message(response.msg);
      }
      
    })
  }

  images = [
    require('../../images/1.jpg'),
    require('../../images/2.jpg'),
    require('../../images/3.jpg'),
    {uri: "http://ot8uv8omp.bkt.clouddn.com/2.png"},
  
  ]

  orderTypes = [
    '综合排序',
    '按回复时间排序',
    '按发表时间排序'
  ]

  selectOrderType() {
    console.log("selectOrderType");
    PullPicker.show(
      '选择排列顺序',
      this.orderTypes,
      this.state.orderType || 0,
      (item, index) => this.setState({orderType: index})
    );
  }


  renderSectionHeader({section}) {
    if (section.content == "forum_info") {
      return null;
    }
    return (
      <View style={[CommonStyles.container]}>
        <View style={[CommonStyles.row, styles.topicFilter]}>
          <Text style={styles.topicFilterActive}>全部</Text>
      
            <TouchableOpacity style={[CommonStyles.row, styles.topicFilterOrder]} onPress={() => this.selectOrderType()}>
              <Text>回复时间排序</Text>
              <Icon name="chevron-down" size={20}/>
            </TouchableOpacity>
       
        </View>
      </View>
     
    )
  }

  viewImage(index) {
    console.log("viewImage: " + index);
    let overlayView = (
      <Overlay.PopView
        style={{}}
        containerStyle={{flex: 1}}
        overlayOpacity={1}
        type='custom'
        customBounds={{x: 10, y: 10, width: 200, height: 400}}
        ref={v => this.fullImageView = v}
      >
        <AlbumView
          style={{flex: 1}}
          control={true}
          images={this.images}
          defaultIndex={1}
          onPress={() => this.fullImageView && this.fullImageView.close()}
          />
        <StatusBar animated={false} hidden={true} />
      </Overlay.PopView>
    );
    Overlay.show(overlayView);
  }

  gotoTopicDetail(item) {
    Actions.CommentScreen({"router_params": {"topic": item}});
  }

  gotoTopicCreate() {
    Actions.TopicCreate({"router_params": {"forum": item}});
  }

  renderForumInfo() {
    return (
      <View style={[CommonStyles.container, styles.sectionHeaderWrapper]}>
        <View style={[CommonStyles.row, styles.sectionHeader]}>
          <View style={[CommonStyles.row, styles.forumInfo]}>
            <Avatar
              rounded 
              large 
              source={{uri: "http://ot8uv8omp.bkt.clouddn.com/1y1FJh2gd51CE2ObcNNhjcuMAVyKV6KmNMrzrxa4.jpeg"}} 
              activeOpacity={0.7} 
              style={styles.forumCover} 
            />
            <View style={[styles.forumDesc]}>
              <Text style={styles.forumName}>{this.state.forumInfo.name}版块</Text>
              <View style={[CommonStyles.row]}>
                <Text style={styles.forumStat}>帖子：100</Text>
                <Text style={styles.forumStat}>回复: 1000</Text>
              </View>
            </View>
          </View>
          <View>
            <Button type="primary" size="small" style={styles.followBtn}>关注</Button>
          </View>
        </View>
      </View>
    )
  }

  renderItem = ({item, index}) => {
    return (
      <View key={item.key} style={[CommonStyles.container, styles.itemWrap]}>
        <View style={[CommonStyles.row, styles.topicHeader]}>
          <Avatar small rounded source={{uri: item.user.data.avatar}} />
          <View>
            <Text style={[styles.nickname]}>{item.user.data.name}</Text>
            <View style={[CommonStyles.row]}>
              <Text style={[styles.updateTime]}>{item.last_comment_time_human}</Text>
              <View style={[CommonStyles.row, styles.countWrap]}>
                <Icon name="comment-outline" />
                <Text style={styles.viewCount}>{item.comment_count}</Text>
              </View>
              <View style={[CommonStyles.row, styles.countWrap]}>
                <Icon name="view-week" />
                <Text style={styles.commentCount}>{item.view_count}</Text>
              </View>
            </View>
          </View>
        </View>
        <TouchableWithoutFeedback onPress={() => this.gotoTopicDetail(item)}>
        <View>
          <View style={styles.contentWrap}>
            <Text>{item.mainFloor.data.detail.data.content}</Text>
          </View>
        {
          item.mainFloor.data.detail.data.attachments ? 
          <View style={[CommonStyles.row, styles.attachmentImageWrap]}>
          {
          item.mainFloor.data.detail.data.attachments.data.map((_image, i, _arr) => {
            return (
              <View key={_image.key}>
                <Image 
                  source={{uri: _image.url}} 
                  style={[styles.attachmentImage, {width: (width-30)/(_arr.length), height: util.getThumbImageHeight(_arr.length)}]}
                />
              </View>
            )
          })
          }
          </View>
          :
          null
        }
        </View>
        </TouchableWithoutFeedback>
      </View>
    )
  }

  itemSeparator = () => {
    return null;
    return (
      <View style={styles.itemSeparator}></View>
    )
  }

  goBack() {
  //  this.props.navigation.navigate("ForumMain");
   this.props.navigation.goBack();
  }

  doFollow() {

  }

  render() {
    let ForumInfo = this.renderForumInfo();
    return (
      <View style={{flex: 1}}>
        {ForumInfo}
        <FlatList
          renderItem = {this.renderItem}
          data={this.state.list}
          refreshing={this.state.loading}
          onRefresh={() => this.onRefresh()}
        />
       
     </View>
    )
  }
}

const styles = StyleSheet.create({
  sectionTopAction: {
    paddingTop: 24,
    justifyContent: "space-between",
    alignItems: "center",
  },
  pagetTitleLeft: {
    alignSelf: "flex-start"
  },
  sectionHeaderWrapper: {
    paddingBottom: 15,
    paddingTop: 15,
    marginBottom: 5,
  },
  sectionHeader: {
    alignItems: "center",
    justifyContent: "space-between",
  },
  forumDesc: {
    marginLeft: 10,
  }, 
  forumInfo: {
    alignItems: "center",
  },
  forumCover: {

  },
  nickname: {
    marginBottom: 5
  },
  updateTime: {
    fontSize: 12,
  },
  viewCount: {
    fontSize: 12,
  },
  commentCount: {
    fontSize: 12,
  },
  forumName: {
    fontSize: 20,
    marginBottom: 5
  },
  forumStat: {
    marginRight: 10,
  },
  followBtn: {
    width: 50,
    height: 30,
  },
  divider: {
    marginTop: 10,
    marginBottom: 10,
  },

  flatList: {
    marginTop: 4,
  },

  itemWrap: {
    marginBottom: 3,
    paddingTop: 10,
    paddingBottom: 10,
  },
  itemSeparator: {
    display: "flex",
    height: 1,
    backgroundColor: "#ddd"
  },
  arrow: {
    position: "absolute",
    right: 0
  },
  countWrap: {
    alignItems: "center",
    marginLeft: 5,
  },
  contentWrap: {
    paddingTop: 10,
    paddingBottom: 10,
  },
  attachmentImage: {
    //height: 100,
  },
  topicFilter: {
    justifyContent: "space-between",
    alignItems: "center",
    paddingTop: 5,
    paddingBottom: 5,
    borderBottomColor: "#eee",
    borderBottomWidth: 1,
  },
  topicFilterActive: {
    borderBottomWidth: 1,
    borderBottomColor: "#000",
  },
  topicFilterOrder: {
    alignItems: "center",
  }
})
